//
//  DBHelper.m
//  Moss
//
//  Created by administrator on 12-1-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DBHelper.h"
#import "DBVersionManager.h"

static DBHelper* instance = nil;

@implementation DBHelper

+ (DBHelper*)getInstance
{
    if(instance==nil){
        instance = [[DBHelper alloc] init];
        instance->mDBMap=[[NSMutableDictionary alloc] init];
        instance->mDBPathMap=[[NSMutableDictionary alloc] init];
    }
    return instance;
}

//内部方法，配置数据库链接
- (void)setupDatabase:(FMDatabase*)db
{
    db.logsErrors = YES;
    db.traceExecution = YES;
}


// 初始化数据库版本
- (void)initDB:(NSString*)dbName
     dbVersion:(int)dbVersion
  AllDBVersion:(int)allDBVersion {
    NSLog(@"init db:%@",dbName);
    NSString* dbFilepath = [FilePathMode getDBPath:dbName];
    NSLog(@"dbFilepath=%@",dbFilepath);
    
    FMDatabaseQueue* dbQueue = [mDBMap objectForKey:dbName];
    if (dbQueue) {
        [dbQueue close];
        [mDBMap removeObjectForKey:dbName];
    }
    //打开数据库
    dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbFilepath];
    DBVersionManager *versionManager = [DBVersionManager sharedInstance];
    
    //检查是否内部初始化过
    if([versionManager isDatabaseHasInitInternal:dbQueue]){
        //业务数据库版本升级
        int curAllTableVersion = [versionManager getCurrAllTableDBVersion:dbQueue];
        if (curAllTableVersion < allDBVersion) {
            
            [versionManager upgradeBusiness:curAllTableVersion newVersion:allDBVersion doneBlock:^(BOOL success) {//成功之后才能将其他的升级
                if (success) {
                    //内部初始化过了,版本数据库升级
                    int currDBVersion = [versionManager getCurrDatabaseVersion:dbQueue];
                    if(currDBVersion < dbVersion){
                        //如果版本号不一致，直接drop掉,重新创建
                        [versionManager dropDBVersionTable];
                        
                        //重新创建
                        [versionManager initDatabaseInternal:dbQueue];
                    }
                }
                NSLog(@"升级%@",success?@"成功":@"失败");
                
            }];
        }
    }
    else{
        //然后，内部初始化一下
        [versionManager initDatabaseInternal:dbQueue];
    }
    [mDBMap setObject:dbQueue forKey:dbName];
    [mDBPathMap setObject:dbFilepath forKey:dbName];
}

- (FMDatabaseQueue*)getDBQueue:(NSString*)dbName
{
    return [mDBMap objectForKey:dbName];
}

- (FMDatabase*)getNewDB:(NSString*)dbName{
    NSLog(@"getNewDB(%@)",dbName);
    NSString* dbFilepath = [mDBPathMap objectForKey:dbName];
    NSLog(@"dbFilepath=%@",dbFilepath);
    if(!dbFilepath) return nil;
    
    //打开数据库
    FMDatabase* db = [FMDatabase databaseWithPath:dbFilepath];
    [db open];
    [self setupDatabase:db];
    return db;
}


- (void)closeDBQueue:(NSString*)dbName
{
    FMDatabaseQueue *dbQueue = [mDBMap objectForKey:dbName];
    if (dbQueue) {
        [dbQueue close];
        [mDBMap removeObjectForKey:dbName];
    }
    
}

- (void)runRead:(void (^)(void))completion
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        readqueue = dispatch_queue_create("readqueue", DISPATCH_QUEUE_SERIAL);
        
    });
    
    dispatch_sync(readqueue, ^{
        completion();
    });
}

- (void)runWrite:(void (^)(void))completion
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        writequeue = dispatch_queue_create("writequeue", DISPATCH_QUEUE_SERIAL);
        
    });
    
    dispatch_sync(writequeue, ^{
        completion();
    });
}


@end
